// pages/kqmystart/kqmystart.js
let total_micro_second = 0;
function countdown(that) {
  that.setData({
    clock: dateformat(total_micro_second)
  });
  if (total_micro_second <= 0) {
    that.setData({
      clock: ['00', '00', '00', '00']
    });
  }
  timetout = setTimeout(function () {
    total_micro_second -= 1000;
    countdown(that);
  }
    , 1000)
}

var timetout = null;

// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60);
  //console.log (day + "天" + hr + "小时" + min + "分钟" + sec + "秒");
  return [day + '', hr + '', min + '', sec + '']
}
let app = getApp();
let wcache = require('../../utils/wcache.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    clock: ['00', '00', '00', '00'],
    courseInfoName: "",
    name: "",
    countdown: "",
    tip: "",
    isBuy: 0,
    year:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    new app.WeToast();
    this.openTime();
    wx.setNavigationBarTitle({
      title: '考前密押',
    })
    this.setData({
      year: new Date().getFullYear()+"年"
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (timetout != null)
      clearTimeout(timetout);
  },

  startTest() {
    if (this.data.countdown == 0) {
      this.wetoast.toast({
        title: this.data.tip,
        duration: 1000
      })
    } else {
      if (this.data.isBuy > 0) {
        wx.navigateTo({
          url: '../exerciselist/exerciselist?type=05',
        })
      }else{
        wx.navigateTo({
          url: '../buy/buy?type=1',
        })
      }
    }
  },

  openTime() {
    app.httpUtils.postLoading(app.Api.GETOPENTIME, {
      uid: app.globalData.userBean().id,
      courseInfoId: wcache.get("courseInfoId", "")
    }).then(res => {
      if (res.code == '00') {
        this.setData({
          courseInfoName: res.data.courseInfoName,
          name: res.data.name,
          countdown: res.data.countdown,
          tip: res.data.tip,
          isBuy: res.data.isBuy,
        })

        if (this.data.countdown == 0) {
          this.wetoast.toast({
            title: res.data.tip,
            duration: 1000
          })
        }else{
          this.total_micro_second = res.data.countdown 
          countdown(this);
        }
      }
    })
  }
})